package com.zb.mobile.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.code.service.ConCodeService;
import com.zb.constant.CodeConstant;
import com.zb.excel.converter.CodeConverter;
import com.zb.entity.*;
import com.zb.mobile.UserCodeOrderInfoVo;
import com.zb.mobile.UserCodeRegisterFieldListVo;
import com.zb.mobile.UserCodeRegisterListVo;
import com.zb.mobile.UserCodeRegisterVo;
import com.zb.mobile.user.service.ConUserMobileCodeService;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.view.ViewGoods;
import com.zb.vo.CodeDetailVo;
import com.zb.vo.UserContactVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author WEN
 * @Date 2023/11/6 0006
 **/
@Service
public class ConUserMobileCodeServiceImpl implements ConUserMobileCodeService {
    @Resource
    private ZjCodeService codeService;
    @Resource
    private ZjCodeUserRegisterService codeUserRegisterService;
    @Resource
    private ViewGoodsService viewGoodsService;
    @Resource
    private ZjUserContactService userContactService;
    @Resource
    private ZjCodeFieldService codeFieldService;
    @Resource
    private ZjCodeFieldContentService codeFieldContentService;
    @Resource
    private ZjCodeInfoService codeInfoService;
    @Resource
    private ZjCodeUserRegisterFieldValService codeUserRegisterFieldValService;
    @Resource
    private ZjUserService userService;
    @Resource
    private ZjCodeScanDetailSetService codeScanDetailSetService;
    @Resource
    private ZjProductIntroduceService productIntroduceService;
    @Resource
    private ZjProductImageService productImageService;
    @Resource
    private ConCodeService conCodeService;

    // 防伪查询 - 根据编码/仓库编码查询
    @Override
    public Map<String, Object> getSecurityCheck(AccounLoginInfo loginInfo, String code) {
        Long id = codeService.getIdByCodeOrStoreCode(loginInfo.getCustAccId(), code);
        Assert.isTrue(null != id && id != 0, "查无此编码的商品数据：" +code);
        ZjCodeInfo codeInfo = codeInfoService.getInfoById(id);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", id);
        resultMap.put("register", codeInfo.getRegister());
        return resultMap;
    }

    // 电子保修卡 - 获取保修卡列表
    @Override
    public Map<String, Object> getUserCodeList(Long userId, PageUtil pageUtil) {
        PageUtil.setPageLimitMobile(pageUtil);
        QueryWrapper<ZjCodeUserRegister> registerQueryWrapper = new QueryWrapper<>();
        registerQueryWrapper.select("id");
        registerQueryWrapper.eq("user_id", userId);
        Page<ZjCodeUserRegister> page = codeUserRegisterService.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), registerQueryWrapper);
        List<Long> codeIds = page.getRecords().stream().map(ZjCodeUserRegister::getId).toList();
        List<ZjCode> codeList = codeService.getUserCodeRegisterByIds(codeIds);

        List<Long> goodsIds = codeList.stream().map(ZjCode::getGoodsId).distinct().toList();
        List<Long> goodsSpecIds = codeList.stream().map(ZjCode::getGoodsSpecId).distinct().toList();
        List<ViewGoods> viewGoodsList = viewGoodsService.getByGoodsIdsAndGoodsSpecIds(goodsIds, goodsSpecIds);
        List<UserCodeRegisterListVo> voList = codeList.stream().map(code -> {
            UserCodeRegisterListVo vo = new UserCodeRegisterListVo();
            BeanUtil.copyProperties(code, vo);
            vo.setCode(code.getSecurityCode());
            vo.setStatus(CodeConverter.codeStatusConverter(code.getStatus(), code.getWarrantyEndTime()));
            viewGoodsList.stream().filter(f -> Objects.equals(1, f.getGoodsType()) && Objects.equals(f.getId(), code.getGoodsId()) && Objects.equals(f.getSpecId(), code.getGoodsSpecId()))
                    .findFirst().ifPresent(specView -> {
                        vo.setGoodsBrand(specView.getBrand());
                        vo.setGoodsModel(specView.getModel());
                        vo.setGoodsName(specView.getName());
                    });
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 电子保修卡 - 获取客户登记地址列表
    @Override
    public Map<String, Object> getUserRegisterAddressList(Long userId, PageUtil pageUtil) {
        PageUtil.setPageLimitMobile(pageUtil);
        QueryWrapper<ZjUserContact> contactQueryWrapper = new QueryWrapper<>();
        contactQueryWrapper.orderByDesc("is_main_contact");
        contactQueryWrapper.select("id", "is_main_contact AS mainContact", "username", "phone", "province", "city", "area", "town", "address");
        contactQueryWrapper.eq("user_id", userId);
        Page<ZjUserContact> page = userContactService.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), contactQueryWrapper);
        List<UserContactVo> voList = page.getRecords().stream().map(c -> {
            UserContactVo vo = new UserContactVo();
            BeanUtil.copyProperties(c, vo);
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 获取编码登记自定义字段
    @Override
    public Map<String, Object> getUserCodeRegisterField(Long custAccId) {
        QueryWrapper<ZjCodeField> codeFieldQueryWrapper = new QueryWrapper<>();
        codeFieldQueryWrapper.orderByDesc("is_required");
        codeFieldQueryWrapper.select("id", "name", "type", "upload_size", "upload_qty", "is_required AS required", "tip");
        codeFieldQueryWrapper.eq("cust_acc_id", custAccId)
                .eq("category", 2)
                .eq("is_disabled", false);
        List<ZjCodeField> codeFieldList = codeFieldService.list(codeFieldQueryWrapper);

        List<Long> codeFieldIds = codeFieldList.stream().map(ZjCodeField::getId).toList();
        List<ZjCodeFieldContent> contentList = codeFieldContentService.getByCodeFieldIds(codeFieldIds);

        return PageUtil.rows(codeFieldList.stream().map(field -> {
            UserCodeRegisterFieldListVo vo = new UserCodeRegisterFieldListVo();
            BeanUtil.copyProperties(field, vo);
            vo.setContents(contentList.stream().filter(f -> Objects.equals(f.getCodeFieldId(), field.getId())).map(ZjCodeFieldContent::getVal).toList());
            return vo;
        }).toList());
    }


    // 增加电子保修卡
    @Override
    @Transactional
    public Map<String, Object> saveUserCodeRegister(AccounLoginInfo logintInfo, UserCodeRegisterVo codeRegisterVo) {
        ZjCodeInfo codeInfo = codeInfoService.getInfoById(codeRegisterVo.getCodeId());
        Assert.isTrue(null != codeInfo, "该商品编码数据不存在");
        Assert.isTrue(!codeInfo.getRegister(), "该商品编码已激活并登记，不可重复登记");
        // 新客户账号ID
        Long newUserId = 0L;
        // 关联登录新账号
        if (codeRegisterVo.getHelpOtherRegister()) {
            newUserId = userService.save(logintInfo,
                    new UserInfo().setName(codeRegisterVo.getName())
                            .setPhone(codeRegisterVo.getPhone())
                            .setProvince(codeRegisterVo.getProvince())
                            .setCity(codeRegisterVo.getCity())
                            .setArea(codeRegisterVo.getArea())
                            .setTown(codeRegisterVo.getTown())
                            .setAddress(codeRegisterVo.getAddress())
            );
            if (codeRegisterVo.getHelpOtherRegister() && Objects.equals(logintInfo.getId(), newUserId)) {
                codeRegisterVo.setHelpOtherRegister(false);
                newUserId = 0L;
            }
        }
        ZjCodeUserRegister register = new ZjCodeUserRegister();
        BeanUtil.copyProperties(codeRegisterVo, register);
        register.setId(codeRegisterVo.getCodeId());
        register.setCustAccId(logintInfo.getCustAccId());
        register.setUserId(codeRegisterVo.getHelpOtherRegister()? newUserId : logintInfo.getId());
        codeUserRegisterService.save(register);
        codeUserRegisterFieldValService.save(logintInfo.getCustAccId(), register.getId(), codeRegisterVo.getRegisterFieldVals());
        codeService.updateCodeInfoByRegister(logintInfo, codeRegisterVo.getCodeId(), "【客户移动报单端】编码激活并登记", "客户【"+ logintInfo.getName() +"】登记并激活商品编码");

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("helpOtherCreateOrder", codeRegisterVo.getHelpOtherRegister());
        resultMap.put("otherUserId", newUserId);
        return resultMap;
    }

    // 工单报单-扫码报单，获取编码信息
    @Override
    public Object getUserOrderCodeInfo(AccounLoginInfo loginInfo, String securityCode) {
        ZjCode code = codeService.getByCode(loginInfo.getCustAccId(), securityCode);
        Assert.isTrue(null != code, "编码 ["+ securityCode +"] 的商品数据不存在");
        ZjCodeInfo codeInfo = codeInfoService.getInfoById(code.getId());
        ViewGoods viewGoods = viewGoodsService.getByGoodsTypeAndGoodsIdAndGoodsSpecId(code.getType(), code.getGoodsId(), code.getGoodsSpecId());

        UserCodeOrderInfoVo vo = new UserCodeOrderInfoVo();
        vo.setId(code.getId());
        vo.setCode(code.getSecurityCode());
        vo.setGoodsId(code.getGoodsId());
        vo.setGoodsSpecId(code.getGoodsSpecId());
        vo.setRegister(codeInfo.getRegister());
        if (codeInfo.getRegister()) {
            ZjCodeUserRegister register = codeUserRegisterService.getById(code.getId());
            vo.setUserId(register.getUserId());
            vo.setUserPhone(register.getPhone());
            vo.setUserName(register.getName());
            vo.setProvince(register.getProvince());
            vo.setCity(register.getCity());
            vo.setArea(register.getArea());
            vo.setTown(register.getTown());
            vo.setAddress(register.getAddress());
            vo.setOtherCode(!Objects.equals(register.getUserId(), loginInfo.getId()));
        }
        vo.setGoodsBrandId(viewGoods.getBrandId());
        vo.setGoodsBrand(viewGoods.getBrand());
        vo.setGoodsModel(viewGoods.getModel());
        vo.setGoodsName(viewGoods.getName());
        vo.setGoodsTypeId(viewGoods.getTypeId());
        vo.setGoodsType(viewGoods.getType());
        vo.setGoodsSpecName(viewGoods.getSpecName());
        vo.setGoodsImage(viewGoods.getImage());
        return vo;
    }

    // 根据编码ID编码扫码详情信息
    @Override
    public Map<String, Object> getUserCodeDetail(Long custAccId, Long codeId) {
        CodeDetailVo code = conCodeService.getInfo(codeId);
        Assert.isTrue(null != code, "此编码商品的数据不存在");
        ViewGoods viewGoods = viewGoodsService.getByGoodsTypeAndGoodsIdAndGoodsSpecId(code.getType(), code.getGoodsId(), code.getGoodsSpecId());
        CodeScanInfoVo infoVo = new CodeScanInfoVo();
        infoVo.setId(codeId);
        infoVo.setGoodsId(code.getGoodsId());
        infoVo.setGoodsSpecId(code.getGoodsSpecId());
        infoVo.setGoodsBrand(code.getBrand());
        infoVo.setGoodsType(viewGoods.getType());
        infoVo.setGoodsName(code.getGoodsName());
        infoVo.setGoodsModel(code.getModel());
        infoVo.setGoodsSpecName(code.getGoodsSpecName());
        infoVo.setGoodsItemNumber(viewGoods.getItemNumber());
        infoVo.setGoodsPrice(viewGoods.getPrice());
        infoVo.setSecurityCode(code.getSecurityCode());
        infoVo.setActiva(code.getActiva());
        infoVo.setActivaTime(code.getActivaTime());
        infoVo.setCodeStatus(code.getStatus());
        infoVo.setWarrantyStartTime(code.getWarrantyStartTime());
        infoVo.setWarrantyEndTime(code.getWarrantyEndTime());
        infoVo.setRegister(code.isRegister());
        infoVo.setRegisterTime(code.getRegisterTime());
        infoVo.setInboundTime(code.getInboundTime());
        infoVo.setOutboundTime(code.getOutboundTime());
        infoVo.setUserName(code.getUsername());
        infoVo.setUserPhone(code.getPhone());
        infoVo.setProvince(code.getProvince());
        infoVo.setCity(code.getCity());
        infoVo.setArea(code.getArea());
        infoVo.setTown(code.getTown());
        infoVo.setAddress(code.getAddress());
        infoVo.setSaleNetwork(code.getNetwork());
        infoVo.setGoodsImage(productImageService.getByProductId(code.getGoodsId()).stream().map(ZjProductImage::getImage).toList());
        infoVo.setGoodsContent(productIntroduceService.getByProductId(code.getGoodsId()));

        // 更新查询次数
        ZjCodeInfo codeInfo = codeInfoService.getInfoById(codeId);
        ZjCodeInfo newCodeInfo = new ZjCodeInfo();
        newCodeInfo.setId(codeInfo.getId());
        if (null == codeInfo.getFirstSelectTime()) {
            newCodeInfo.setFirstSelectTime(new Date());
        }
        newCodeInfo.setLastSelectTime(new Date());
        newCodeInfo.setSelectNum(codeInfo.getSelectNum() +1);
        codeInfoService.updateById(CodeConstant.tableType(codeId), newCodeInfo);

        infoVo.setSelectNum(newCodeInfo.getSelectNum());
        infoVo.setFirstSelectTime(null != codeInfo.getFirstSelectTime()? codeInfo.getFirstSelectTime() : newCodeInfo.getFirstSelectTime());
        infoVo.setLastSelectTime(code.getLastSelectTime());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("codeScanInfo", codeScanDetailSetService.getDetail(custAccId));
        resultMap.put("infoVal", infoVo);
        return resultMap;
    }

}
